<template>
  <headPage></headPage>
  <div class="seach-wrap">
    <el-form :inline="true" ref="" :model="params" label-width="100px" style="display: flex;flex-direction: column;justify-content: space-evenly;height: 100%;width: 100%">
      <div>
        <!--      <el-form-item label="基于日志条数:">-->
        <!--        <el-input-number :min="100" v-model="countParam" clearable style="width: 100%" placeholder="请输入日志条数"></el-input-number>-->
        <!--      </el-form-item>-->
        <el-form-item label="工号:">
          <el-input v-model="params.staffAccount" clearable style="width: 100%" placeholder="请输入工号"></el-input>
        </el-form-item>
        <el-form-item label="时间:">
          <el-date-picker
              v-model="params.dateTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              size="default"
              clearable
          />
        </el-form-item>
        <el-form-item label="状态:">
          <el-select
              clearable
              v-model="params.status"
              placeholder="请选择状态"
              style="width: 120px"
          >
            <el-option value="1" label="执行成功"></el-option>
            <el-option value="0" label="执行失败"></el-option>
            <el-option value="2" label="未返回数据"></el-option>
          </el-select>
        </el-form-item>
        <el-button type="danger" :loading="createLoading"  @click="getLlmTrainData"><el-icon><Document /></el-icon>&nbsp;生成模型训练数据</el-button>
        <el-button type="primary" @click="findLlmTrainList"><el-icon><Search /></el-icon>&nbsp;查询</el-button>
        <el-button type="primary" :loading="exportLoading"  @click="exportLlmTrainText"><el-icon><Download /></el-icon>&nbsp;导出模型训练数据</el-button>
      </div>
<!--      <div>-->
<!--        <el-form-item label="开始:">-->
<!--          <el-input-number v-model="params.startCount" clearable style="width: 100%" placeholder="请输入"></el-input-number>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="结束:">-->
<!--          <el-input-number v-model="params.endCount" clearable style="width: 100%" placeholder="请输入"></el-input-number>-->
<!--        </el-form-item>-->
<!--        <el-button type="primary" @click="findLlmTrainList"><el-icon><Search /></el-icon>&nbsp;查询</el-button>-->
<!--        <el-button type="primary" :loading="exportLoading"  @click="exportLlmTrainText"><el-icon><Download /></el-icon>&nbsp;导出模型训练数据</el-button>-->
<!--      </div>-->

    </el-form>
  </div>
  <div style="padding: 0rem .2rem">
    <el-table
        :data="dataItems"
        stripe
        v-loading="loading"
        :header-cell-style="{background:'#F5F7FA',color:'#333333'}"
        style="width: 100%;"
    >
      <el-table-column
          prop="id"
          label="序号">
      </el-table-column>
      <el-table-column
          prop="message"
          label="输出状态">
        <template #default="scope">
          <span v-if="scope.row.status==1" style="color: green">
            {{scope.row.message}}
          </span>
          <span v-else-if="scope.row.status==2" style="color: darkorange">
            {{scope.row.message}}
          </span>
          <span v-else style="color: red">
            {{scope.row.message}}
          </span>
        </template>
      </el-table-column>
      <el-table-column
          prop="creator"
          label="创建人">
      </el-table-column>
      <el-table-column
          prop=""
          label="创建时间">
        <template #default="scope">
          {{scope.row.creatime?mon(scope.row.creatime):''}}
        </template>
      </el-table-column>
      <el-table-column
          prop="updator"
          label="更新人">
      </el-table-column>
      <el-table-column
          prop=""
          label="更新时间">
        <template #default="scope">
          {{scope.row.updatime?mon(scope.row.updatime):''}}
        </template>
      </el-table-column>
      <el-table-column
          prop=""
          label="是否更新">
        <template #default="scope">
          <span v-if="scope.row.ifUpdate==1" style="color: green">
            {{node_table_option_desc[scope.row.ifUpdate]}}
          </span>
          <span v-else style="color: red">
            {{node_table_option_desc[scope.row.ifUpdate]}}
          </span>
        </template>
      </el-table-column>
      <el-table-column
          prop=""
          width="150"
          label="操作">
        <template #default="scope">
          <el-button type="primary" size="small" @click="updateItem(scope.row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        background
        layout="prev, pager, next, jumper"
        @current-change="handleCurrentChange"
        :current-page.sync="params.startIndex"
        :page-size="params.pageSize"
        :total="params.totalNum"
    >
    </el-pagination>
  </div>
  <el-dialog v-if="dialogDataVisible" v-model="dialogDataVisible" title="JSON编辑" width="800"  class="json-edit-dialog">
    <json-editor-vue
        language="zh-CN"
        v-model="jsonData"
        :readonly="true"
        class="editor"
        :current-mode="currentMode"
        :colorPicker="true"
        @validationError="validationError"
        @change="changeJson"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogDataVisible = false">取消</el-button>
        <el-button type="primary" :disabled="disabled" v-loading.fullscreen.lock="loading" @click="jsonSure">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { findLlmTrainList,updateLlmTrain,exportLlmTrainText,assembleJson } from '@/api/chartdb'
import consts from '../../common/consts'
import headPage from '../ui/headPage.vue'
import moment from 'moment'
import { ElMessage } from 'element-plus'
import JsonEditorVue from 'json-editor-vue3'
export default {
  name: 'llmTrain',
  components: {
    headPage,JsonEditorVue
  },
  props:{},
  data(){
    return {
      countParam:'',
      loading:false,
      exportLoading:false,
      createLoading:false,
      dataItems:[],
      params:{
        startIndex:1,
        pageSize:10,
        totalNum:0,
        startCount:undefined,
        endCount:undefined,
        staffAccount:'',
        dateTime:'',
        startDate:'',
        endDate:'',
        status:'',
      },
      currentInfo:{},
      dialogDataVisible:false,
      currentMode:"code",
      jsonData:"",
      jsonSystem:"",
      disabled:false,
      node_table_option_desc:consts.node_table_option_desc,
    }
  },
  mounted() {
    this.findLlmTrainList()
  },
  methods: {
    exportLlmTrainText:function(){
      this.exportLoading=true
      if(this.params.dateTime&&this.params.dateTime.length==2){
        this.params.startDate=moment(this.params.dateTime[0]).format("YYYY-MM-DD")
        this.params.endDate=moment(this.params.dateTime[1]).format("YYYY-MM-DD")
      }
      exportLlmTrainText(this.params).then((res) => {
        var reader = new FileReader();
        reader.onload = (e) => {
          console.log("开始下载");
          //下载
          let data = res.data;
          if (!data) {
            return;
          }
          var blob = new Blob([data], {
            type: "text/plain;charset=UTF-8",
          });
          var url = window.URL.createObjectURL(blob);
          var aLink = document.createElement("a");
          aLink.style.display = "none";
          aLink.href = url;
          aLink.setAttribute("download", "模型训练数据.json");
          document.body.appendChild(aLink);
          aLink.click();
          //下载完成移除元素
          document.body.removeChild(aLink);
          //释放掉blob对象
          window.URL.revokeObjectURL(url);
        };
        reader.readAsText(res.data);
        this.exportLoading=false
      }).catch(function (error) {
            console.log(error);
      })
    },
    getLlmTrainData:function(){
      this.$confirm('是否生成模型训练数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.createLoading=true
        this.currentInfo.json=this.jsonData
        if(this.params.dateTime&&this.params.dateTime.length==2){
          this.params.startDate=moment(this.params.dateTime[0]).format("YYYY-MM-DD")
          this.params.endDate=moment(this.params.dateTime[1]).format("YYYY-MM-DD")
        }
        let param={
          startDate:this.params.startDate,
          endDate:this.params.endDate,
          status:this.params.status,
          staffAccount:this.params.staffAccount,
        }
        assembleJson(param).then((res) => {
          ElMessage({
            showClose: true,
            message: '完成！',
            type: 'success',
          })
          this.createLoading=false
          this.findLlmTrainList()
        })
      }).catch(() => {
      });
    },
    mon(date){
      return moment(date).format("YYYY-MM-DD HH:mm:ss")
    },
    findLlmTrainList:function(){
      this.loading=true
      console.log("this.params.dateTime===>",this.params.dateTime)
      if(this.params.dateTime&&this.params.dateTime.length==2){
        this.params.startDate=moment(this.params.dateTime[0]).format("YYYY-MM-DD")
        this.params.endDate=moment(this.params.dateTime[1]).format("YYYY-MM-DD")
      }else {
        this.params.startDate=""
        this.params.endDate=""
      }
      let param={
        startDate:this.params.startDate,
        endDate:this.params.endDate,
        startIndex:this.params.startIndex,
        pageSize:this.params.pageSize,
      }
      findLlmTrainList(param).then((res) => {
        this.dataItems=res.data.data.records
        this.params.totalNum=res.data.data.total
        this.params.startIndex=res.data.data.current
        this.params.pageSize=res.data.data.size
        this.loading=false
      })
    },
    handleCurrentChange:function (startIndex) {
      var vm = this;
      vm.params.startIndex = startIndex;
      vm.findLlmTrainList();
    },
    updateItem:function(row){
      this.currentInfo=row
      let paramsStr=row.json
      this.jsonData=JSON.parse(paramsStr)
      this.jsonSystem=this.jsonData.system
      delete this.jsonData.system
      delete this.jsonData.input;
      this.dialogDataVisible=true
    },
    jsonSure(){
      this.$confirm('是否标记为已更新?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.currentInfo.json=this.jsonData
        this.currentInfo.json.system=this.jsonSystem
        this.currentInfo.json.input=""
        if(!this.currentInfo.json.history){
          this.currentInfo.json.history=[]
        }
        updateLlmTrain({ id:this.currentInfo.id,json:this.currentInfo.json }).then((res) => {
          ElMessage({
            showClose: true,
            message: '保存成功！',
            type: 'success',
          })
          this.dialogDataVisible=false
          this.handleCurrentChange(this.params.startIndex)
        })
      }).catch(() => {
      });
    },
    validationError:function(e) {
      this.$nextTick(()=>{
        if(e&&e.lastSchemaErrors.length>0){
          this.disabled=true
        }else{
          this.disabled=false
        }
      })
    },
    changeJson:function(e) {
      this.disabled=false
    },
    colorPicker:function(e){
      console.log("eeee===>",e)
    }
  }
}
</script>

<style lang="scss" scoped>
.seach-wrap{
  display: flex;
  align-items: center;
  height: 0.6rem;
  //justify-content: flex-end;
  padding: 0 0.2rem;
  .el-form-item{
    margin-bottom: 0px !important;
  }
}
.dialog-footer{
  height: .3rem;
  display: flex;
  align-items: center;
  justify-content: center;
}
.container{
  height: 100% !important;
}
:deep(.json-editor-vue .jsoneditor-modes){
  display: none !important;
}
:deep(.json-editor-vue .jsoneditor-sort){
  display: none !important;
}
:deep(.json-editor-vue .jsoneditor-transform){
  display: none !important;
}
:deep(.json-editor-vue .jsoneditor-poweredBy){
  display: none !important;
}
.full-screen{
  right:15px !important;
}


</style>